import './lookinghome.scss'
import IndexCom from '../../components/index/IndexCom'
type Props = { history:any }
import Searchbox from '../../components/searchBox/Searchbox'
import Houseitem from '../../components/houseItem/Houseitem'
import {CaretDownOutlined,SearchOutlined,CompassOutlined,LeftOutlined} from '@ant-design/icons'
import { Popup, Toast, CascadePickerView} from 'antd-mobile'
import { useEffect, useMemo, useState } from 'react'
import axios from 'axios'
import { PickerValue } from 'antd-mobile/es/components/picker-view'
export default function Lookinghome(props: Props) {

  let url:string = 'http://localhost:8080'


  useEffect(() => {
    getHouselist()
    document.querySelector('.content')?.addEventListener('scroll',pagescroll)
    return () => {
      document.querySelector('.content')?.removeEventListener('scroll',pagescroll)
      console.log('组件被销毁；');
      
    }
  }, [])


  // 是否吸顶
  const [xd, setxd] = useState(false)
  // 页面滚动事件
    const pagescroll = () => {
      let content = document.querySelector('.content') as HTMLDivElement;
      let key = content.scrollTop;
      if(key >= 40){
        setxd(true)
      }else{
        setxd(false)
      }
    }



  // 当前城市
  const currentCity = JSON.parse(window.sessionStorage.getItem('currentCity') || JSON.stringify({label:"广州",value:"AREA|e4940177-c04c-383d",pinyin:"guangzhou", short:"gz"}))



  // 房屋列表
  const [houselist, setHouselist] = useState<any>([]);
// 获取当前房屋列表
  const getHouselist = async (q=`cityId=${currentCity.value}`) => {
    let {data:{body:data}} = await axios.get( url + '/houses?' + q)
    setHouselist(data.list)
    Toast.show({
      content: `共找到 ${data.count} 套房源`,
    })
  }

  


  // 房屋筛选
  // 筛选列表变量
  const [shaixuanCon, setShiaxuanCon] = useState<any>([])

  // 获取筛选列表
  const getSxList = async (e:any) => {
    let obj = e.target.dataset;
    if(obj.name){
      if(obj.name === 'sx'){
        if(!shaixuanCon.length){
          let list = []
          let {data:{body:data}} = await axios.get( url + '/houses/condition?id='+currentCity.value)
          data.area.children.map((item:any) => {
            item.children && item.children.map((subitem:any) => {
                if(subitem.children) delete subitem.children
                return subitem
              })
              return item            
          })
          list.push(
            [],
            [data.area,data.subway],
            data.rentType,
            data.price,
            [
              {name:"户型",data:data.roomType},
              {name:"朝向",data:data.oriented},
              {name:"楼层",data:data.floor},
              {name:"房屋亮点",data:data.characteristic}
            ]
          )
          setShiaxuanCon(list)
          console.log(list);          
        }

        setVisible(parseInt(obj.index))
      }
    }    
  }
  

type queryType = {
  cityId:string,
  area:string,
  subway:string,
  rentType:string,
  price:string,
  start:string,
  end:string,
  more:[]
}

  // 筛选条件查询
  let [query,setQuery] = useState<queryType>({
    cityId:currentCity.value,
    area:'null', // 地区
    subway:'null', // 地铁
    rentType:"null", // 整租
    price:'null',  // 价格
    start:'1',  // 开始项
    end:'20',  // 结束项
    more:[], // 复合查询
  })

  // 当前筛选条件查看
  const [visible, setVisible] = useState(0)

  const shaixuanList = [{name:'区域', key:"area"},{name:'方式',key:"rentType"},{name:'租金',key:"price",},{name:'筛选',key:"more"}]


  // 是否已筛选样式
  const shaixuanStyle = (item:any) => {
    if(item.key !== 'more'){
      if(item.key === 'area'){
        if(query.area !== 'null' || query.subway !== 'null'){
          return  { color: "#21b97a" }
        }
        return { color:"#000" }
      }else{
        if(query[item.key] !== 'null'){
          return { color: "#21b97a" }
        }
        return { color:"#000" }
      }
    }else{
      if(query[item.key].length){
        return { color : "#21b97a" }
      }
      return { color : "#000" }
    }
  }

  // 选择器改变事件
  const pickerChange = (value:PickerValue[])=>{
    let newquery = {...query}
    if(visible === 1){
      if(value[value.length-1] !== 'null'){
        newquery.area = 'null'
        newquery.subway = 'null'
        String(value[0]) === 'area' ? newquery.area = String(value[2]) : newquery.subway = String(value[2])
          
      }else{
        newquery.area = 'null'
        newquery.subway = 'null'
        String(value[0]) === 'area' ? newquery.area = String(value[1]) : newquery.subway = String(value[1])
      }
    }else if(visible === 2){
      newquery.rentType = 'null'
      newquery.rentType = String(value[0])
    }else if(visible === 3){
      newquery.price = 'null'
      newquery.price = String(value[0])
    }else{
      
    }
    setQuery(newquery)
  }


  // 筛选取消按钮
  const cancel = ()=>{
    setQuery({
      cityId:currentCity.value,
      area:'null', // 地区
      subway:'null', // 地铁
      rentType:"null", // 整租
      price:'null',  // 价格
      start:'1',  // 开始项
      end:'20',  // 结束项
      more:[], // 复合查询
    })
    setVisible(0)
  }

  // 筛选前三项确认按钮
  const finishSx = ()=>{
    let list = []
    for (let key in query) {
      if(query[key] !=='more'){
        if(query[key] !== 'null'){
          list.push(`${key}=${query[key]}`)
        }
      }else{
        if(query.more.length){
          let str = query.more.join(',')
          list.push(`more=${str}`)
        }
      }
    }
    let q = list.join('&')
    getHouselist(q)
    setVisible(0)
  }

  // 筛选最后一项清除按钮
  const clearShaixuan3 = () => {
    let newQuery = {...query}
    newQuery.more = []
    setQuery(newQuery)
  }


  // 筛选最后一项内部标签点击事件
  const selectTag = (e:any) => {
    let key = e.target.dataset;
    let newQuery = {...query}
    if(key){
      if(key.name === 'sxtag'){
        let bol = newQuery.more.findIndex(item => item === key.value)
        if(bol !== -1){
          newQuery.more.splice(bol, 1)
        }else{
          newQuery.more.push(key.value)
        }
        setQuery(newQuery)
      }
    }
  }


  return (
    <div className='lookhome'>
      {
        Boolean(visible) && (
          <div className='mark' onClick={()=>setVisible(0)}></div>
        )
      }
      <div className='content'>
        {/* 搜索框 */}
        <Searchbox history={props.history}>
            {
              (goPush:any) =>(
                <div className='search'>
                  <div className='goback'>
                    <LeftOutlined onClick={()=>props.history.goBack()}/>
                  </div>
                  <div className='searchItem'>
                    <div className='selector' onClick={()=>goPush('/citylist','/lookinghome')}>
                      <span>{ currentCity.label }</span>
                      <CaretDownOutlined />
                    </div>
                    <div className='icon'>|</div>
                    <div className='searchor' onClick={()=>goPush('/search')}>
                    <SearchOutlined />
                    <span>请输入小区或地址</span>
                    </div>
                  </div>
                  <div className='map'>
                    <CompassOutlined style={{ color:"#00AE66" }} onClick={()=>goPush('/map')}/>
                  </div>
                </div>
              )
            }
        </Searchbox>
        {/* 选项卡 */}
        <div className='shaixuanBox' style={ xd ? {position:"fixed", top:"0" , left:"0",width:"100%", zIndex:"11"} : {position:'relative',width:"100%"} } onClick={(e)=>getSxList(e)}>
          <div className='shaixuan'>
            {
              shaixuanList.map((item,index) =>(
                <div 
                style={ shaixuanStyle(item) } 
                key={item.key} 
                data-index={index+1} 
                data-name="sx">
                  {item.name}
                  <CaretDownOutlined  
                  data-name="sx" 
                  data-index={index+1}/>
                </div>
              ))
            }
            {
              (visible < 4 && visible > 0) && (
                  <div className='maskContentAndBtn'>
                    <div className='shaixuan2'  onClick={(e)=>getSxList(e)}>
                      {
                        shaixuanList.map((item,index) =>(
                          <div style={ index+1 === visible ? { color: "#21b97a" } : { color : 'black' }} key={index} data-index={index+1} data-name="sx">{item.name}<CaretDownOutlined  data-name="sx" data-index={index+1}/></div>
                        ))
                      }
                    </div>
                    <div className='maskContent'>
                      <CascadePickerView options={shaixuanCon[visible]} onChange={pickerChange}/>
                    </div>
                    <div className='maskBtn'>
                        <button onClick={cancel}>取消</button>
                        <button onClick={finishSx}>确定</button>
                    </div>
                  </div>
              )
            }
          </div>
        </div>
        <Popup
        visible={visible === 4}
        onMaskClick={() =>setVisible(0)}
        position='right'
        bodyStyle={{ width: '80vw' }}
        >
          <div onClick={(e)=>selectTag(e)} className='shaixuan3' style={{ height:"calc( 100vh - 0.5rem )", overflowY:"scroll", padding:" 0 20px" }}>
            {
              shaixuanCon[visible] && shaixuanCon[visible].map((item:any, index:number) =>(
                <div className='shaixuanitem' key={index+1000}>
                  <div className='title'>{item.name}</div>
                  <div className='children'>
                    {
                      item.data && item.data.map((subitem:any, index:number) => (
                        <div
                         data-value={subitem.value} 
                         data-name="sxtag" 
                         key={index+100}
                         className={query.more.includes(subitem.value) ? 'active' : ''}>
                          {subitem.label}
                        </div>
                      ))
                    }
                  </div>
                </div>
              ))
            }
          </div>
          <div className='popupbtn'>
              <div className='clear' onClick={clearShaixuan3}>清除</div>
              <div className='finished' onClick={finishSx}>确定</div>
          </div>
        </Popup>
        <Houseitem houselist={houselist}/>
      </div>
      <IndexCom/>
    </div>
  )
}